package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDocument;
import com.ruoyi.common.core.domain.entity.SysDocumentCategory;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// SysDocumentController.java
@RestController
@RequestMapping("/system/document")
public class SysDocumentController extends BaseController {
    @Autowired
    private ISysDocumentService documentService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询文档列表
     */
    @PreAuthorize("@ss.hasPermi('system:document:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDocument document) {
        startPage();
        List<SysDocument> list = documentService.selectDocumentList(document);
        return getDataTable(list);
    }

    /**
     * 导出文档列表
     */
    @PreAuthorize("@ss.hasPermi('system:document:export')")
    @Log(title = "文档管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysDocument document) {
        List<SysDocument> list = documentService.selectDocumentList(document);
        ExcelUtil<SysDocument> util = new ExcelUtil<SysDocument>(SysDocument.class);
        return util.exportExcel(list, "文档数据");
    }

    /**
     * 获取文档详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:document:query')")
    @GetMapping(value = "/{documentId}")
    public AjaxResult getInfo(@PathVariable("documentId") Long documentId) {
        return AjaxResult.success(documentService.selectDocumentById(documentId));
    }

    /**
     * 新增文档
     */
    @PreAuthorize("@ss.hasPermi('system:document:add')")
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysDocument document) throws IOException {
        //if (!file.isEmpty()) {
            //String filePath = FileUploadUtils.upload(file); // 使用Ruoyi的文件上传工具
            //document.setFilePath(filePath);
            //document.setFileSize(file.getSize());
            //document.setDocumentType(FileTypeUtils.getExtension(file.getOriginalFilename()));
            document.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
        //}
        return toAjax(documentService.insertDocument(document));
    }

    /**
     * 修改文档
     */
    @PreAuthorize("@ss.hasPermi('system:document:edit')")
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysDocument document) {
        return toAjax(documentService.updateDocument(document));
    }

    /**
     * 删除文档
     */
    @PreAuthorize("@ss.hasPermi('system:document:remove')")
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{documentIds}")
    public AjaxResult remove(@PathVariable Long[] documentIds) {
        return toAjax(documentService.deleteDocumentByIds(documentIds));
    }

    @PostMapping(value="/removeByPath")
    public AjaxResult removeByPath(@RequestBody SysDocument document) {
        String filePath = document.getFilePath().replace(serverConfig.getUrl(),"");
        String fileName = document.getDocumentName();
        return toAjax(documentService.deleteDocumentByPath(filePath,fileName));
    }

    /**
     * 下载文档
     */
    @PreAuthorize("@ss.hasPermi('system:document:download')")
    @GetMapping("/download/{documentId}")
    public void download(@PathVariable Long documentId, HttpServletResponse response) {
        try {
            SysDocument document = documentService.selectDocumentById(documentId);
            if (document == null) {
                throw new RuntimeException("文档不存在");
            }

            String filePath = document.getFilePath().replace("/profile", RuoYiConfig.getProfile());
            String fileName = document.getDocumentName() + "." + document.getDocumentType();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文档失败", e);
            throw new RuntimeException("下载文档失败");
        }
    }

    /**
     * 文件上传
     */
    @PreAuthorize("@ss.hasPermi('system:document:upload')")
    @Log(title = "文档上传", businessType = BusinessType.OTHER)
    @PostMapping(value="/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            if (!file.isEmpty()) {
                String filePath = FileUploadUtils.upload(file);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", filePath);
                ajax.put("fileName", file.getOriginalFilename());
                return ajax;
            }
            return AjaxResult.error("上传文件异常，请联系管理员");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    

    //@PreAuthorize("@ss.hasPermi('system:document:category:list')")
    @GetMapping("/category/list")
    public AjaxResult list(SysDocumentCategory category) {
        List<SysDocumentCategory> list = documentService.selectCategoryList(category);
        return success(list);
    }

    /**
     * 获取文档分类树结构
     */
    //@PreAuthorize("@ss.hasPermi('system:document:category:tree')")
    @GetMapping("/category/tree")
    public AjaxResult tree() {
        List<SysDocumentCategory> list = documentService.selectCategoryList(new SysDocumentCategory());
        return success(documentService.buildCategoryTree(list));
    }

    /**
     * 获取文档分类详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:document:category:query')")
    @GetMapping(value = "/category/{categoryId}")
    public AjaxResult getCategoryInfo(@PathVariable("categoryId") Long categoryId) {
        return success(documentService.selectCategoryById(categoryId));
    }

    /**
     * 新增文档分类
     */
    //@PreAuthorize("@ss.hasPermi('system:document:category:add')")
    @Log(title = "文档分类", businessType = BusinessType.INSERT)
    @PostMapping(value = "/category")
    public AjaxResult add(@RequestBody SysDocumentCategory category) {
        return toAjax(documentService.insertCategory(category));
    }

    /**
     * 修改文档分类
     */
    //@PreAuthorize("@ss.hasPermi('system:document:category:edit')")
    @Log(title = "文档分类", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/category")
    public AjaxResult edit(@RequestBody SysDocumentCategory category) {
        return toAjax(documentService.updateCategory(category));
    }

    /**
     * 删除文档分类
     */
    //@PreAuthorize("@ss.hasPermi('system:document:category:remove')")
    @Log(title = "文档分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/category/{categoryId}")
    public AjaxResult remove(@PathVariable Long categoryId) {
        if (documentService.hasChildByCategoryId(categoryId)) {
            return error("存在子分类,不允许删除");
        }
        return toAjax(documentService.deleteCategoryById(categoryId));
    }

    /**
     * 获取分类下拉树列表
     */
    /*@GetMapping("/category/treeselect")
    public AjaxResult treeselect(SysDocumentCategory category) {
        List<SysDocumentCategory> categories = documentService.selectCategoryList(category);
        return success(documentService.buildCategoryTreeSelect(categories));
    }*/
}